package com.bkd.dreams.client;

import com.bkd.dreams.client.event.EventTable;
import com.bkd.dreams.client.login.LoginInfo;
import com.bkd.dreams.client.login.LoginRenderer;
import com.bkd.dreams.client.login.NotLoggedInException;
import com.bkd.dreams.client.login.service.LoginService;
import com.bkd.dreams.client.login.service.LoginServiceAsync;
import com.bkd.dreams.client.stand.StandRoleTable;
import com.bkd.dreams.client.stand.StandTable;
import com.bkd.dreams.client.volunteer.VolunteerTable;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class AchievingDreams implements EntryPoint {

	private LoginInfo loginInfo = null;
	
	private TabPanel tabPanel = new TabPanel();
	
	private EventTable eventTable = new EventTable();
	private StandRoleTable standRoleTable = new StandRoleTable();
	private StandTable standTable = new StandTable();
	private VolunteerTable volunteerTable = new VolunteerTable();
	private LoginRenderer loginRenderer = new LoginRenderer();

	@Override
	public void onModuleLoad() {
	    // Check login status using login service.
	    LoginServiceAsync loginService = GWT.create(LoginService.class);
	    loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
	      public void onFailure(Throwable error) {
	    	  handleError(error);
	      }

	      public void onSuccess(LoginInfo result) {
	        loginInfo = result;
	        if(loginInfo.isLoggedIn()) {
	        	if(loginInfo.isRegistered()) {
	        		loginRenderer.loadWhoAmI(loginInfo);
	        		eventTable.setVolunteer(loginInfo.getVolunteer());
	        		eventTable.loadTable(tabPanel);
	        		volunteerTable.loadTable(tabPanel);
	        		standRoleTable.loadTable(tabPanel);
	        		standTable.loadTable(tabPanel);
			        RootPanel.get("eventList").add(tabPanel);
	        	} else {
	        		loginRenderer.loadWhoAmI(loginInfo);
	        		loginRenderer.loadRegistration(loginInfo, eventTable, tabPanel);
	        	}
	        } else {
	        	loginRenderer.loadLogin(loginInfo);
	        }
	      }
	    });
	}

	private void handleError(Throwable error) {
		Window.alert(error.getMessage());
		if (error instanceof NotLoggedInException) {
			Window.Location.replace(loginInfo.getLogoutUrl());
		}
	}
}
